package com.xinsoft.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

import static cn.hutool.core.collection.CollUtil.newArrayList;

/**
 * @ClassName Swagger3Config
 * @Description Swagger配置类
 * @Author lijie
 * @Date 2022/10/10 10:22 星期一
 * @Version 1.0
 */
@Configuration
public class Swagger3Config implements WebMvcConfigurer {
    @Bean
    public Docket docket() {
        //返回文档摘要信息
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class).or(RequestHandlerSelectors.basePackage("com.xinsoft")))
                .paths(PathSelectors.any())
                .build().
                        securitySchemes(newArrayList(
                                new ApiKey("Authorization", "Authorization", "header")
                        ))
                .securityContexts(contexts(platformAuth()));
    }

    /**
     * 生成接口信息，包括标题、联系人等
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("芯软工业互联网V7.0.1接口文档")
                .description("如有疑问，请联系芯软。")
                .termsOfServiceUrl("https://www.wxxinsoft.com")
                .contact(new Contact("Li9527", "https://www.wxxinsoft.com",""))
                .version("1.0")
                .build();
    }

    private List<SecurityContext> contexts(List<SecurityReference> auth) {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(auth)
                        .build());
        return securityContexts;
    }

    private List<SecurityReference> platformAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "all");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }
}
